import { fetch } from 'plugins/axios'

export function loadHeaders ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/getmodels/', {
      appname: 'salt',
      modelname: 'Salt_grains'
    }).then((response) => {
      commit('headerSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function loadTable ({state, commit}) {
  return new Promise((resolve, reject) => {
    state.loading = true
    const {sortBy, descending, page, rowsPerPage} = state.serverPagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/salt/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search
    }).then((response) => {
      commit('loadTableSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function openSaltView ({state, commit}, payload) {
  let url = '/salt/' + payload + '/'
  fetch(url, {
  }).then((response) => {
    commit('openSuccess', response)
  }).catch((error) => {
    alert(error.response)
  })
  state.dialog = true
}
